import { BYTEDANCE, WECHAT } from "cc/env";
import { AudioMgr } from "./AudioMgr";
import { ICallBack, IUser } from "./DataMgr";
import { uuid } from "../Util";

export class SdkMgr {
    public static _ins: SdkMgr = null

    public static get ins() {
        if (null == this._ins) {
            this._ins = new SdkMgr();
        }
        return this._ins
    }

    shareMsg: string = '超级魔性的游戏，你敢接受挑战吗？'
    shareImg: string = ''
    // 激励视频广告
    adVideoId: string = 'adunit-62b8cded4c4d38b4'
    private videoAd = null
    // 插屏广告
    adInterstitialId: string = 'adunit-a985dd00e5663f95'
    private interstitialAd = null
    // 横幅广告
    adBannerId: string = 'adunit-af8125052d96a105'
    private bannerAd = null
    // 原生格子: 横向（默认90%多格子）
    adCustomRowId: string = 'adunit-44d2c5fa787d9c49'
    private customRowAd = null
    // 原生格子: 纵向（默认矩阵格子）
    adCustomColId: string = ''
    private customColAd = null

    // 获取平台
    getPlatform() {
        let platform = null
        if (WECHAT) {
            platform = window['wx']
        } else if (BYTEDANCE) {
            platform = window['tt']
        }
        return platform
    }

    // 主动分享
    // query: string (eg: key1=val1&key2=val2)
    activeShare(options: { title?: string, imageUrl?: string, query?: string } = { title: '', imageUrl: '', query: '' }) {
        const platform = this.getPlatform()
        if (!platform) return
        options.title = options.title || this.shareMsg
        options.imageUrl = options.imageUrl || this.shareImg
        platform.shareAppMessage(options);
    }

    // 被动分享
    passiveShare(options: { title?: string, imageUrl?: string, query?: string } = { title: '', imageUrl: '', query: '' }) {
        const platform = this.getPlatform()
        if (!platform) return
        platform.showShareMenu()
        options.title = options.title || this.shareMsg
        options.imageUrl = options.imageUrl || this.shareImg
        platform.onShareAppMessage(() => {
            return options
        });
    }

    // 获取分享参数
    getShareQuery(key: string) {
        const platform = this.getPlatform()
        if (!platform) return
        const options = platform.getLaunchOptionsSync()
        const query = options.query
        let data = null
        if (query && query[key]) {
            data = query[key]
        }
        return data
    }

    // 跳转
    turnToApp(appId: string) {
        if (appId == '') return
        const platform = this.getPlatform()
        if (!platform) {
            // 传地址浏览器跳转
            window.open(appId)
            return
        }
        platform.navigateToMiniProgram({
            appId: appId
        });
    }

    // 监听音频中断（微信）
    initAudioEndListener() {
        if (typeof window['wx'] === 'undefined') return
        window['wx'].onAudioInterruptionEnd(() => {
            AudioMgr.ins.playMusic()
        })
    }

    // 初始化横幅
    initBannerAd() {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.adBannerId == '') return
        let winSize = platform.getSystemInfoSync();
        if (this.bannerAd == null) {
            this.bannerAd = platform.createBannerAd({
                adUnitId: this.adBannerId,
                adIntervals: 30,
                style: {
                    height: winSize.windowHeight - 80,
                    left: 0,
                    top: 500,
                    width: winSize.windowWidth
                }
            });
            this.bannerAd.onResize((res: any) => {
                this.bannerAd.style.top = winSize.windowHeight - this.bannerAd.style.realHeight;
                this.bannerAd.style.left = winSize.windowWidth / 2 - this.bannerAd.style.realWidth / 2;
            });
            this.bannerAd.onError((err: any) => {
                console.error('【流量主横幅】初始化错误')
            });
        }
    }

    // 横幅展示
    toggleBannerAd(isShow: boolean) {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.bannerAd) {
            isShow ? this.bannerAd.show() : this.bannerAd.hide();
        }
    }

    // 初始化插屏
    initInterstitialAd() {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.adInterstitialId == '') return
        if (this.interstitialAd == null) {
            this.interstitialAd = platform.createInterstitialAd({
                adUnitId: this.adInterstitialId
            });
            this.interstitialAd.onError((err: any) => {
                console.error('【流量主插屏】初始化错误')
            });
        }
    }

    // 插屏展示
    showInterstitialAd() {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.interstitialAd) {
            this.interstitialAd.show().catch((err: any) => {
                console.error('【流量主插屏】加载错误')
            });
        }
    }

    // 初始化激励
    initVideoAd() {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.adVideoId == '') return
        if (this.videoAd == null) {
            this.videoAd = platform.createRewardedVideoAd({
                adUnitId: this.adVideoId
            });
            this.videoAd.onError((err: any) => {
                console.error('【流量主激励】初始化错误')
            });
        }
    }

    // 激励展示
    showVideoAd(success: any, fail?: any) {
        const platform = this.getPlatform()
        if (!platform) {
            return success && success('模拟激励奖励发放')
        }
        if (this.videoAd) {
            this.videoAd.offClose();
            this.videoAd.onClose((res: any) => {
                this.videoAd.offClose();
                if (res && res.isEnded || res === undefined) {
                    return success && success('激励奖励已经发放')
                } else {
                    return fail && fail('激励奖励播放中断')
                }
            });
            this.videoAd.show().catch(() => {
                this.videoAd.load()
                    .then(() => this.videoAd.show())
                    .catch((err: any) => {
                        console.log('激励奖励展示失败')
                    })
            });
        } else {
            return fail && fail('该功能尚未开放')
        }
    }

    // 初始化横向格子
    initCustomRowAd() {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.adCustomRowId == '') return
        let winSize = platform.getSystemInfoSync();
        if (this.customRowAd == null) {
            this.customRowAd = platform.createCustomAd({
                adUnitId: this.adCustomRowId,
                adIntervals: 30,
                style: {
                    width: 320,
                    left: (winSize.screenWidth - 320) / 2,
                    top: winSize.screenHeight - 100,
                    fixed: 0
                }
            })
            this.customRowAd.onError((err: any) => {
                console.error('【流量主横向格子】初始化错误')
            });
        }
    }

    // 横向格子广告展示
    toggleCustomRowAd(isShow: boolean = true) {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.customRowAd) isShow ? this.customRowAd.show() : this.customRowAd.hide();
    }

    // 初始化纵向格子
    initCustomColAd() {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.adCustomColId == '') return
        let winSize = platform.getSystemInfoSync();
        if (this.customColAd == null) {
            this.customColAd = platform.createCustomAd({
                adUnitId: this.adCustomColId,
                adIntervals: 30,
                style: {
                    width: winSize.screenWidth - 20,
                    left: 10,
                    top: (winSize.screenHeight - 350) / 2,
                    fixed: 0
                }
            })
            this.customColAd.onError((err: any) => {
                console.error('【流量主纵向格子】初始化错误')
            });
        }
    }

    // 横向格子广告展示
    toggleCustomColAd(isShow: boolean = true) {
        const platform = this.getPlatform()
        if (!platform) return
        if (this.customColAd) isShow ? this.customColAd.show() : this.customColAd.hide();
    }

    // 获取登录code（后续服务器兑换openid）
    getLoginCode(callback?: (param: ICallBack) => void) {
        const obj: ICallBack = { status: false, data: null, msg: '服务器存在异常' }
        window['wx'].login({
            success(res: any) {
                if (res.code) {
                    obj.status = true
                    obj.data = res.code
                    obj.msg = '成功获取'
                    callback && callback(obj)
                } else {
                    callback && callback(obj)
                }
            },
            fail() {
                callback && callback(obj)
            }
        })
    }

    // 获取授权信息
    getLoginInfo(callback?: (param: ICallBack) => void) {
        if (typeof window['wx'] === 'undefined') return
        const obj: ICallBack = { status: false, data: null, msg: '服务器存在异常' }
        window['wx'].getSetting({
            success(res: any) {
                if (res.authSetting["scope.userInfo"]) {
                    window['wx'].getUserInfo({
                        success(res: any) {
                            const info = res.userInfo
                            const user: IUser = { openid: uuid(), nickname: info.nickName, gender: info.gender, avatar: info.avatarUrl }
                            obj.status = true
                            obj.data = user
                            obj.msg = '已授权'
                            callback && callback(obj)
                        },
                        fail() {
                            callback && callback(obj)
                        }
                    })
                } else {
                    const sys = window['wx'].getSystemInfoSync()
                    const width = sys.screenWidth
                    const height = sys.screenHeight
                    let button = window['wx'].createUserInfoButton({
                        type: 'text',
                        text: '',
                        style: {
                            left: 0,
                            top: 0,
                            width: width,
                            height: height,
                            backgroundColor: '#00000000',
                            color: '#ffffff',
                            fontSize: 20,
                            textAlign: 'center',
                            lineHeight: height,
                        }
                    })
                    const tapEvent = function (res: any) {
                        button.destroy()
                        if (res.userInfo) {
                            const info = res.userInfo
                            const user: IUser = { openid: uuid(), nickname: info.nickName, gender: info.gender, avatar: info.avatarUrl }
                            obj.status = true
                            obj.data = user
                            obj.msg = '接受授权'
                            callback && callback(obj)
                        } else {
                            obj.msg = '拒绝授权'
                            callback && callback(obj)
                        }
                    }
                    button.onTap(tapEvent)
                }
            },
            fail() {
                callback && callback(obj)
            }
        })
    }

    // 不经过授权生成登录信息
    getLoginInfoLocal(callback?: (param: ICallBack) => void) {
        const obj: ICallBack = { status: true, data: null, msg: '用户数据' }
        const time = new Date().getTime()
        let nickname = `${time}`
        nickname = 'USER.' + nickname.substring(nickname.length - 4)
        const user: IUser = { openid: uuid(), nickname: nickname, gender: 0, avatar: '' }
        obj.data = user
        callback && callback(obj)
    }
}


